package com.cqie.hospitalescort.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Aspect
@Component
public class AvoidRepeatSubmitAspect {

    private final Map<String, Long> timestamps = new ConcurrentHashMap<>();

    @Before("@annotation(AvoidRepeatSubmit)")
    public void noRepeatSubmit(JoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        AvoidRepeatSubmit annotation = method.getAnnotation(AvoidRepeatSubmit.class);
        int interval = annotation.interval();

        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String sessionId = request.getSession().getId();
        String key = sessionId + "-" + method.getName();

        long currentTime = System.currentTimeMillis();
        if (timestamps.containsKey(key)) {
            long lastTime = timestamps.get(key);
            if (currentTime - lastTime < interval) {
                throw new RuntimeException("请勿频繁操作");
            }
        }

        timestamps.put(key, currentTime);
    }
}
